/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pa165.languageschoolpresentation;

import com.pa165.languageschoolpersistence.Exceptions.ServiceFailureException;
import com.pa165.languageschoolservice.DTO.LectureDTO;
import com.pa165.languageschoolservice.DTO.StudentDTO;
import com.pa165.languageschoolservice.service.LectureService;
import com.pa165.languageschoolservice.service.StudentService;
import java.text.SimpleDateFormat;
import java.util.List;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Jiri Uhlir
 */
@UrlBinding("/students/{$event}/{studentDTO.id}/{lectureDTO.id}")
public class StudentActionBean implements ActionBean {

    final static Logger log = LoggerFactory.getLogger(StudentActionBean.class);
    private ActionBeanContext context;
    @SpringBean
    protected StudentService studentService;
    @SpringBean
    protected LectureService lectureService;
    @ValidateNestedProperties(value = {
        @Validate(on = {"saveAdd", "saveEdit"}, field = "name", required = true),
        @Validate(on = {"saveAdd", "saveEdit"}, field = "surname", required = true),
        @Validate(on = {"saveAdd", "saveEdit"}, field="userName", required=true, minlength=1, maxlength=255),
        @Validate(on = {"saveAdd", "saveEdit"}, field="pwd", required=true, minlength=3, maxlength=255)
    })
    private StudentDTO studentDTO;
    private LectureDTO lectureDTO;
    private SimpleDateFormat sdfSource = new SimpleDateFormat(LectureActionBean.FORMATSTRING);

    public StudentService getStudentService() {
        return studentService;
    }

    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;


    }

    public LectureService getLectureService() {
        return lectureService;
    }

    public void setLectureService(LectureService lectureService) {
        this.lectureService = lectureService;
    }

    public StudentDTO getStudentDTO() {
        return studentDTO;
    }

    public void setStudentDTO(StudentDTO studentDTO) {
        this.studentDTO = studentDTO;
    }

    public LectureDTO getLectureDTO() {
        return lectureDTO;
    }

    public void setLectureDTO(LectureDTO lectureDTO) {
        this.lectureDTO = lectureDTO;
    }

    public SimpleDateFormat getSdfSource() {
        return sdfSource;
    }

    public void setSdfSource(SimpleDateFormat sdfSource) {
        this.sdfSource = sdfSource;
    }

    public Resolution add() {
        log.debug("add() studentDTO={}", studentDTO);
        return new ForwardResolution("/student/addStudent.jsp");
    }

    public Resolution saveAdd() throws ServiceFailureException{
        log.debug("add() studentDTO={}", studentDTO);
        studentService.add(studentDTO);
        return new RedirectResolution(this.getClass(), "all");
    }

    @DefaultHandler
    public Resolution all() {
        log.debug("all()");
        return new ForwardResolution("/student/student.jsp");
    }

    public Resolution delete() throws ServiceFailureException{
        log.debug("delete({})", studentDTO.getId());
        studentService.remove(studentDTO);
        return new RedirectResolution(this.getClass(), "all");
    }

    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "saveEdit", "enrollStudent", "showLectures"})
    public void loadStudentFromDatabase() throws ServiceFailureException{
        String ids = context.getRequest().getParameter("studentDTO.id");
        if (ids == null) {
            return;
        }
        studentDTO = studentService.get(Long.parseLong(ids));
    }

    public Resolution edit() {
        log.debug("edit() student={}", studentDTO);
        return new ForwardResolution("/student/editStudent.jsp");
    }

    public Resolution saveEdit() throws ServiceFailureException{
        log.debug("saveEdit() studentDTO={}", studentDTO);
        studentService.modify(studentDTO);
        return new RedirectResolution(this.getClass(), "all");
    }

    public List<StudentDTO> getStudents() throws ServiceFailureException{
        return studentService.getAll();
    }

    public Resolution showLectures() {
        log.debug("showLectures()");
        return new ForwardResolution("/student/studentLectures.jsp");
    }

    public List<LectureDTO> getLectures() throws ServiceFailureException{
        log.debug("getLectures() studentDTO={}", studentDTO);
        return lectureService.getLectures(studentDTO);
    }

    public List<LectureDTO> getAllLectures() {
        log.debug("getAllLectures()");
        return lectureService.getAll();
    }

    public Resolution enroll() {
        log.debug("enroll()");
        return new ForwardResolution("/student/enrollStudentToLecture.jsp");
    }

    public Resolution enrollToLecture() {
        log.debug("enrollStudent()", studentDTO, lectureDTO);
        try {
            studentService.enrollStudentToLecture(lectureDTO, studentDTO);
            //return new RedirectResolution(this.getClass(), "all");
            return getContext().getSourcePageResolution();
        } catch ( ServiceFailureException e) {
            ValidationErrors errors = new ValidationErrors();
            errors.add("lecture", new LocalizableError("lecture.empty"));
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
    }

    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }
    
     public Resolution showLecturesByLogin() {
        log.debug("showLecturesByLogin()");
        return new ForwardResolution("/student/studentLectures.jsp");
    }
    @Before(stages = LifecycleStage.BindingAndValidation, on = { "showLecturesByLogin"})
    public void loadStudentByLogin() throws ServiceFailureException{
        String login = context.getRequest().getUserPrincipal().getName();//context.getRequest().getParameter("studentDTO.username");
        if (login == null) {
            return;
        }
        studentDTO = studentService.getByLogin(login);
    }
}